package cn.haoran.config;

import cn.haoran.modules.sys.service.SysConfigService;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * mongoDb数据库配置
 */
@Configuration
public class MongoDbConfig {
    protected static Logger logger= LoggerFactory.getLogger("mongoDb数据库配置");
    @Autowired
    SysConfigService sysConfigService;
    @Bean
   /* mongoDb连接配置 */
    MongoClient mongoClient(){
        logger.info("正在获取mongoDb数据配置信息");
        String config = sysConfigService.getValue("mongoDb");
        Gson gson = new Gson();
        HashMap map = new HashMap();
        map = gson.fromJson(config, map.getClass());
        /* host */
        String host = (String) map.get("host");
        /* 端口 */
        String port = (String) map.get("port");
        return new MongoClient(host,Integer.parseInt(port));
    }
    @Bean
    /* 数据工厂配置 */
    MongoDbFactory mongoDbFactory(MongoClient mongoClient){
        String config = sysConfigService.getValue("mongoDb");
        Gson gson = new Gson();
        HashMap map = new HashMap();
        map = gson.fromJson(config, map.getClass());
        /* 数据库名称 */
        String database = (String) map.get("database");
        return new SimpleMongoDbFactory(mongoClient,database);
    }
    @Bean
    /* 模板配置 */
    MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory){
        return new MongoTemplate(mongoDbFactory);
    }
}
